﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SomeKit
{
    /// <summary>
    /// Helper class with extension methods to combine delegates.
    /// </summary>
    public static class DelegateHelper
    {
        /// <summary>
        /// Combines a sequence of delegates.
        /// </summary>
        /// <param name="firstAction">First method.</param>
        /// <param name="action2">Subsequent methods.</param>
        /// <returns>A delegate that combines them all.</returns>
        public static Action Chain(this Action firstAction, params Action[] subsequentActions)
        {
            return () =>
            {
                if (firstAction != null) firstAction();
                if (subsequentActions != null)
                    foreach (var action in subsequentActions)
                        action();
            };
        }

        /// <summary>
        /// Combines a sequence of delegates.
        /// </summary>
        /// <typeparam name="T">The type of the argument for the delegates.</typeparam>
        /// <param name="firstAction">First method.</param>
        /// <param name="action2">Subsequent methods.</param>
        /// <returns>A delegate that combines them all.</returns>
        public static Action<T> Chain<T>(this Action<T> firstAction, params Action<T>[] subsequentActions)
        {
            return param =>
            {
                if (firstAction != null) firstAction(param);
                if (subsequentActions != null)
                    foreach (var action in subsequentActions)
                        action(param);
            };
        }
    }
}
